package com.itheima.jdbctemplate;


import com.itheima.domain.Admin;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * JdbcTemplate => CRUD
 */
public class JdbcTemplateDemo2 {

    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jdbcTemplate = ac.getBean("jdbcTemplate", JdbcTemplate.class);
//        jdbcInsert(jdbcTemplate);
//        jdbcUpdate(jdbcTemplate);
//        jdbcDelete(jdbcTemplate);
//        jdbcFindOne(jdbcTemplate);
//        jdbcFindAll(jdbcTemplate);
        jdbcFindObject(jdbcTemplate);
    }


    public static void jdbcInsert(JdbcTemplate jdbcTemplate) {
        int update = jdbcTemplate.update(
                "insert into admin(username, address, money) values(?, ?, ?)",
                "yanweifeng",
                "china",
                100.00
        );
        System.out.println(update);
    }

    public static void jdbcUpdate(JdbcTemplate jdbcTemplate) {
        int update = jdbcTemplate.update(
                "update admin set username = ?, address = ?, money = ? where id = ?",
                "updateYwf",
                "china-HeNan",
                200.00,
                5
        );
        System.out.println(update);
    }

    public static void jdbcDelete(JdbcTemplate jdbcTemplate) {
        int update = jdbcTemplate.update("delete from admin where id = ?", 5);
        System.out.println(update);
    }

    public static void jdbcFindOne(JdbcTemplate jdbcTemplate) {
        List<Admin> query = jdbcTemplate.query(
                "select * from admin where id = ?",
                new BeanPropertyRowMapper<Admin>(Admin.class),
                4
        );
    }

    public static void jdbcFindAll(JdbcTemplate jdbcTemplate) {
        List<Admin> query = jdbcTemplate.query(
                "select * from admin",
                new BeanPropertyRowMapper<Admin>(Admin.class)
        );
        System.out.println(query);

    }


    public static void jdbcFindObject(JdbcTemplate jdbcTemplate) {
        Integer count = jdbcTemplate.queryForObject(
                "select count(*) from admin",
                Integer.class
        );
        System.out.println(count);

    }


}
